package com.example.xianji.activity;

import java.util.ArrayList;
import java.util.HashMap;

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.Request.Method;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.JsonObjectRequest;
import com.example.xianji.Contant;
import com.example.xianji.XJApplication;
import com.example.xianji.R;
import com.example.xianji.bean.Service;
import com.example.xianji.constant.Constant;
import com.example.xianji.utils.sp.PreferenceEngine;

import android.os.Bundle;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.app.Activity;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

/**
 * 添加友链页面
 */
public class Main_Add_Friend_LianJieActivity extends Activity implements OnClickListener {

    private RelativeLayout add_relative_friend_lianjie_back;
    private TextView submit_friend_lianjie, create_lianjie_text;
    //    private SharedPreferences sp;
//    private Editor ed;
    private EditText edittext_friend_lianjie_wangzhi, edittext_friend_lianjie_name, edittext_friend_lianjie_miaoshu;
    private Button button_lianjie_shunxu;
    private int sort = 6;
    private LinearLayout layout;
    private ListView show_listview;
    private PopupWindow show_popupWindow;
    private ArrayList<Service> list = new ArrayList<Service>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        setContentView(R.layout.activity_main__add__friend__lian_jie);
        add_relative_friend_lianjie_back = (RelativeLayout) findViewById(R.id.add_relative_friend_lianjie_back);
        submit_friend_lianjie = (TextView) findViewById(R.id.submit_friend_lianjie);
        edittext_friend_lianjie_miaoshu = (EditText) findViewById(R.id.edittext_friend_lianjie_miaoshu);
        edittext_friend_lianjie_wangzhi = (EditText) findViewById(R.id.edittext_friend_lianjie_wangzhi);
        edittext_friend_lianjie_name = (EditText) findViewById(R.id.edittext_friend_lianjie_name);
        create_lianjie_text = (TextView) findViewById(R.id.create_lianjie_text);
        button_lianjie_shunxu = (Button) findViewById(R.id.button_lianjie_shunxu);

        add_relative_friend_lianjie_back.setOnClickListener(this);
        button_lianjie_shunxu.setOnClickListener(this);
        submit_friend_lianjie.setOnClickListener(this);
//        sp = getSharedPreferences("text", MODE_PRIVATE);
//        ed = sp.edit();
        list.clear();
        Service mService = new Service();

        Service mService2 = new Service();
        Service mService3 = new Service();
        Service mService4 = new Service();
        Service mService5 = new Service();
        Service mService6 = new Service();
        mService.setStatus(0);
        mService.setName("最前");

        mService2.setStatus(2);
        mService2.setName("较前");
        mService3.setStatus(3);
        mService3.setName("中部");
        mService4.setStatus(4);
        mService4.setName("较后");
        mService5.setStatus(5);
        mService5.setName("最后");
        mService6.setStatus(6);
        mService6.setName("默认");
        list.add(mService);
        list.add(mService2);
        list.add(mService3);
        list.add(mService4);
        list.add(mService5);
        list.add(mService6);
        if (getIntent().getIntExtra("add_friend_lianjie", 0) == Contant.product_vip_lianjie_editor) {
            //链接编辑
            create_lianjie_text.setText("编辑友链");
            sort = getIntent().getIntExtra("friend_lianjie_sort", 100);
            edittext_friend_lianjie_miaoshu.setText(getIntent().getStringExtra("friend_lianjie_description"));
            edittext_friend_lianjie_wangzhi.setText(getIntent().getStringExtra("friend_lianjie_url"));
            edittext_friend_lianjie_name.setText(getIntent().getStringExtra("friend_lianjie_name"));
            //顺序的排列显示

            if (getIntent().getIntExtra("friend_lianjie_sort", 100) == 0 || getIntent().getIntExtra("friend_lianjie_sort", 100) == 1) {
                button_lianjie_shunxu.setText("最前");
            } else if (getIntent().getIntExtra("friend_lianjie_sort", 100) == 2) {
                button_lianjie_shunxu.setText("较前");
            } else if (getIntent().getIntExtra("friend_lianjie_sort", 100) == 3) {
                button_lianjie_shunxu.setText("中部");
            } else if (getIntent().getIntExtra("friend_lianjie_sort", 100) == 4) {
                button_lianjie_shunxu.setText("较后");
            } else if (getIntent().getIntExtra("friend_lianjie_sort", 100) == 5) {
                button_lianjie_shunxu.setText("最后");
            } else {
                button_lianjie_shunxu.setText("默认");
            }
        } else {
            create_lianjie_text.setText("添加友链");
        }
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.add_relative_friend_lianjie_back) {
            Main_Add_Friend_LianJieActivity.this.finish();
        } else if (v.getId() == R.id.submit_friend_lianjie) {
            //提交

            if (edittext_friend_lianjie_name.getText().toString().length() > 0) {
                if (edittext_friend_lianjie_wangzhi.getText().toString().length() > 0) {
                    if (edittext_friend_lianjie_miaoshu.getText().toString().length() > 0) {
                        if (getIntent().getIntExtra("add_friend_lianjie", 0) == Contant.product_vip_lianjie_editor) {
                            //编辑友链
                            editor_lianjie();
                        } else {
                            //添加友链
                            submit_lianjie();
                        }

                    } else {
                        Toast.makeText(Main_Add_Friend_LianJieActivity.this, "请先填写友链描述", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(Main_Add_Friend_LianJieActivity.this, "请先填写友链网址", Toast.LENGTH_SHORT).show();
                }
            } else {
                Toast.makeText(Main_Add_Friend_LianJieActivity.this, "请先填写友链名称", Toast.LENGTH_SHORT).show();
            }

        } else if (v.getId() == R.id.button_lianjie_shunxu) {
            Photo_show();


            show_popupWindow.showAtLocation(findViewById(R.id.relative_create_friend_lianjie), Gravity.BOTTOM, 0, 0);
            show_listview.setAdapter(new MyAdapter());

            show_listview.setOnItemClickListener(new OnItemClickListener() {

                @Override
                public void onItemClick(AdapterView<?> parent, View view,
                                        int position, long id) {
                    sort = list.get(position).getStatus();
                    button_lianjie_shunxu.setText(list.get(position).getName());
                    if (show_popupWindow != null) {
                        show_popupWindow.dismiss();
                    }

                }
            });
        }
    }

    public void submit_lianjie() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("url", edittext_friend_lianjie_wangzhi.getText().toString());//链接
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("name", edittext_friend_lianjie_name.getText().toString());//名称
        map.put("description", edittext_friend_lianjie_miaoshu.getText().toString());//描述
        map.put("sort", sort);//顺序

        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.add_lianjie,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_Add_Friend_LianJieActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        Main_Add_Friend_LianJieActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    public void editor_lianjie() {
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("url", edittext_friend_lianjie_wangzhi.getText().toString());//链接
        map.put("id", getIntent().getIntExtra("friend_lianjie_id", 0));//链接
        map.put("token", PreferenceEngine.getInstance().getString(Constant.SP.NAME, Constant.SP.KEY_XIANJI_TOKEN, ""));
        map.put("name", edittext_friend_lianjie_name.getText().toString());//名称
        map.put("description", edittext_friend_lianjie_miaoshu.getText().toString());//描述
        map.put("sort", sort);//顺序

        JSONObject params = new JSONObject(map);
        JsonObjectRequest request = new JsonObjectRequest(Method.POST, Contant.editor_friend_lianjie,
                params, new Listener<JSONObject>() {

            @Override
            public void onResponse(JSONObject response) {
                try {
                    Toast.makeText(Main_Add_Friend_LianJieActivity.this, response.getString("msg"), Toast.LENGTH_SHORT).show();
                    if (response.getInt("status") == 1) {
                        Contant.product_friend_lianjie_editor_finish = 1;
                        Main_Add_Friend_LianJieActivity.this.finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        }, new Response.ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        XJApplication.getHttpQueues().cancelAll("abcPost");
        request.setTag("abcPost");
        request.setRetryPolicy(new DefaultRetryPolicy(50 * 1000, 1, 1.0f));
        XJApplication.getHttpQueues().add(request);
        XJApplication.getHttpQueues().start();
    }

    private void Photo_show() {
        layout = (LinearLayout) LayoutInflater.from(
                Main_Add_Friend_LianJieActivity.this).inflate(
                R.layout.information_shoow_photo, null);
        show_listview = (ListView) layout.findViewById(R.id.information_photo_listview);

        show_listview.setCacheColorHint(0);

        // listView������
        //listview.setDivider(null); // ������Ŀ֮��ķָ���Ϊnull
        //listView.setAlpha(0.8f);

        show_popupWindow = new PopupWindow(layout, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT);

        show_popupWindow.setBackgroundDrawable(new BitmapDrawable());


        show_popupWindow.setHeight(400);
        show_popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        show_popupWindow.update();
        // ����popupWindow��������������Ӧ�����¼�
        show_popupWindow.setOutsideTouchable(true);
        // ����popupWindow.setFocusable(true);
        // ����������popupWindow����Ĳ��ֿؼ���õ�����¼�������ͱ����ĸ���view�������ˡ�
        show_popupWindow.setFocusable(true);
        show_popupWindow.setContentView(layout);

    }

    class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int arg0) {
            return arg0;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            Holder mHolder;
            if (convertView == null) {
                mHolder = new Holder();
                convertView = View.inflate(Main_Add_Friend_LianJieActivity.this, R.layout.listview_item_layout, null);
                mHolder.place_text = (TextView) convertView.findViewById(R.id.place_text);
                convertView.setTag(mHolder);
            }
            mHolder = (Holder) convertView.getTag();
            mHolder.place_text.setText(list.get(position).getName());

            return convertView;
        }
    }

    class Holder {
        TextView place_text;


    }
}
